#!/usr/bin/env python2.6

import sys
import re
import time
import logging
from smtplib import SMTP
from email.mime.text import MIMEText
from optparse import OptionParser
from os.path import basename
from urllib import urlencode
from urllib2 import *

parser = OptionParser(usage = '%prog [options]', version = '1.0')
parser.add_option('-s', '--status-dat', default = '/var/nagios/status.dat')
options, args = parser.parse_args()
filename = options.status_dat

MAX_INTERVAL = 2000
LOG = '/var/log/' + basename(sys.argv[0])[:-3] + '.log'
logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s: %(message)s',
        filename = LOG,
        filemode = 'a')

url = 'http://sysadmin.douban.com/nagios/cgi-bin/cmd.cgi'
user = ''
passwd = ''
passmgr = HTTPPasswordMgrWithDefaultRealm()
passmgr.add_password(None, url, user, passwd)
handler = HTTPDigestAuthHandler(passmgr)
opener = build_opener(handler)
install_opener(opener)

def getserviceinfos():
    global filename
    # a service info block
    service_info_re = re.compile(r'servicestatus *\{.*?host_name=([^ ]+).*?service_description=([^ ]+).*?last_check=([^ ]+).*?next_check=([^ ]+).*?\}')

    f = file(filename, 'r')
    content = f.read()
    f.close()
    content = content.replace('\n', ' ')
    return service_info_re.findall(content)

def mail(to, msg):
    from_email = 'sysadmin@douban.com'
    to_email = to
    msg = MIMEText(msg)
    msg['Subject'] = 'Nagios interval check'
    msg['From'] = from_email
    msg['To'] = to_email[0]
    msg['Cc'] = ','.join(to_email[1:])
    smtp = SMTP('mail3.douban.com')
    smtp.sendmail(from_email, to_email, msg.as_string())
    smtp.quit

def reschedule(host, service):
    global url
    postdata = {
        'cmd_typ':'7',
        'cmd_mod':'2',
        'host':host,
        'service':service,
        'start_time':time.strftime('%m-%d-%Y %H:%M:%S', time.localtime((time.time()+3000))),
        'force_check':'checked'}
    urlopen(url, urlencode(postdata))
    
def check():
    service_info_s = getserviceinfos()
    infos = []
    for host_name, service_description, last_check, next_check in service_info_s:
        interval = ( int(next_check) - int(last_check)) / 60 # minute
        if interval > MAX_INTERVAL:
            reschedule(host_name, service_description)
            infos.append('HOST: %s, SERVICE: %s, LAST_CHECK: %s, NEXT_CHECK: %s' % \
                  (host_name, service_description, time.ctime(float(last_check)), \
                   time.ctime(float(next_check))))
    if infos:
        for info in infos:
            logging.info(info)
        mail(['huohao@douban.com', 'flex@douban.com'], '\n'.join(infos))
            
def main():
    check()

if __name__ == '__main__':
    main()
